<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="key">
        <el-input
          v-model="queryParams.key"
          placeholder="客户/合同名称/合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.bus_contract_audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="录入时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:contract:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="客户" width="180px" align="center" prop="enterpriseName" />
      <el-table-column label="合同名称" width="180px" align="center" prop="contractName" />
      <el-table-column label="合同编号" align="center" prop="contractNumber" />
      <el-table-column label="合同金额（单位：万元）" width="180px" align="center" prop="contractAmount" :show-overflow-tooltip="true"/>
      <el-table-column label="合同开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电子附件" align="center" prop="contractAnnex" >
        <template slot-scope="scope">
          <el-button
            type="warning"
            plain
            icon="el-icon-audit"
            size="mini"
            @click="handleDownload(scope.row.contractAnnex,scope.row.fileName)"
          >下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="录入人" align="center" prop="entryPerson" />
      <el-table-column label="录入时间" align="center" prop="entryTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.entryTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_contract_audit_status"
                    :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否盖章" align="center" prop="isStamp">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_contract_stamp_status"
                    :value="scope.row.isStamp"/>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="isCancel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_contract_cancel_status"
                    :value="scope.row.isCancel"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300px">
        <template slot-scope="scope" >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status != 1 && scope.row.isCancel == 0"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:contract:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 1 && scope.row.isCancel == 0 && scope.row.isStamp == 0"
            icon="el-icon-edit"
            @click="handleStamp(scope.row)"
            v-hasPermi="['business:contract:remove']"
          >确认盖章</el-button>
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          v-if="scope.row.status == 0 && scope.row.isCancel == 0"
          @click="handleSuccess(scope.row)"
          v-hasPermi="['business:contract:remove']"
        >审核通过</el-button>
        <el-button
          size="mini"
          type="text"
          v-if="scope.row.status == 0 && scope.row.isCancel == 0"
          icon="el-icon-edit"
          @click="handleFailed(scope.row)"
          v-hasPermi="['business:contract:remove']"
        >审核不通过</el-button>
        <el-button
          size="mini"
          type="text"
          v-if="scope.row.isCancel == 0 && scope.row.isStamp == 0"
          icon="el-icon-delete"
          @click="handleDelete(scope.row)"
          v-hasPermi="['business:contract:remove']"
        >作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客户" prop="enterpriseName">
          <el-select v-model="form.enterpriseName" placeholder="选择客户" clearable>
            <el-option
              v-for="item in this.customsList"
              :key="item.enterpriseName"
              :label="item.enterpriseName"
              :value="item.enterpriseName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="合同金额" prop="contractAmount">
          <el-input min="0" type="number" v-model="form.contractAmount" placeholder="请输入合同金额 (单位: 万元)" />
        </el-form-item>
        <el-form-item label="合同开始日期" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择合同开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同结束日期" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择合同结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电子附件: " prop="contractAnnex">
          <el-upload
            ref="upfile"
            :on-remove="handleDeleteFire"
            action="upload"
            style="display: inline"
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="fileList"
            :limit="1"
          >
            <el-button type="success">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {statusFailed,statusSuccess,updateStamp, listContract, getContract, delContract, addContract, updateContract } from "@/api/business/contract";
import { getEnterprise } from "@/api/business/enterpriseInfo";

export default {
  name: "Contract",
  dicts: ['bus_contract_audit_status', "bus_contract_stamp_status", "bus_contract_cancel_status"],
  data() {
    return {
      dateRange:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //客户信息
      customsList:[],
      // 总条数
      total: 0,
      // 合同管理表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      //电子附件文件
      fileList : [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        key:null,
        status:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enterpriseName:[
          {required: true, message: "客户不能为空",trigger:"blur"}
        ],
        contractName:[
          {required: true, message: "合同名称不能为空",trigger:"blur"},
          { min: 1, max: 100, message: '合同名称长度必须在100位以内', trigger: 'blur' }
        ],
        contractNumber:[
          {required: true, message: "合同编码不能为空",trigger:"blur"},
          { min: 1, max: 50, message: '合同编码长度必须在50位以内', trigger: 'blur' }
        ],
        contractAmount:[
          {required: true, message: "合同金额不能为空",trigger:"blur"},
        ],
        startTime:[
          {required: true, message: "合同开始日期不能为空",trigger:"blur"},
        ],
        endTime:[
          {required: true, message: "合同结束日期不能为空",trigger:"blur"},
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAllCustom();
  },
  methods: {
    handleDeleteFire(file,fileList){
      this.fileList=[]
    },
    //文件上传
    handleChange(file,fileList){
      this.fileList=fileList
    },
    //审核通过
    handleSuccess(row) {
      this.$modal.confirm('是否确认审核通过?').then(function() {
        return statusSuccess(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核已通过");
      }).catch(() => {});
    },
    //审核不通过
    handleFailed(row) {
      this.$modal.confirm('是否确认审核不通过?').then(function() {
        return statusFailed(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核不通过");
      }).catch(() => {});
    },
    //盖章
      handleStamp(row) {
        this.$modal.confirm('是否确认盖章?').then(function() {
          return updateStamp(row.id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("盖章成功");
        }).catch(() => {});
      },
    //电子附件下载
    handleDownload(base64String, fileName) {
      const byteCharacters = atob(base64String);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const file = new Blob([byteArray], { type: 'application/octet-stream' });
      const fileUrl = URL.createObjectURL(file);
      const a = document.createElement('a');
      a.href = fileUrl;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(fileUrl);
      }, 0);
    },
    //查询所有客户信息
    getAllCustom(){
      getEnterprise().then(resp=>{
        this.customsList=resp.rows;
      })
    },
    /** 查询合同管理列表 */
    getList() {
      this.loading = true;
      listContract(this.addDateRange(this.queryParams,this.dateRange)).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.fileList=[];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        enterpriseName: null,
        contractName: null,
        contractNumber: null,
        contractAmount: null,
        startTime: null,
        endTime: null,
        contractAnnex: null,
        entryPerson: null,
        entryTime: null,
        updateTime: null,
        status: 0,
        isStamp: null,
        isCancel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList=[];
      this.reset();
      this.open = true;
      this.title = "添加合同管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.id
      getContract(id).then(response => {
        this.form = response.data;

        this.open = true;
        this.title = "修改合同管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let formData = new FormData();
      if (this.form.id !=null){
        formData.append("id",this.form.id)
      }
      if (this.fileList[0] != null){
        formData.append("file",this.fileList[0].raw)
        formData.append("fileName",this.fileList[0].name);
        formData.append("fileSize",this.fileList[0].size);
      }
      formData.append("enterpriseName",this.form.enterpriseName)
      formData.append("contractName",this.form.contractName)
      formData.append("contractNumber",this.form.contractNumber)
      formData.append("contractAmount",this.form.contractAmount)
      formData.append("startTime",this.form.startTime)
      formData.append("endTime",this.form.endTime)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContract(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.fileList = [];
              this.getList();
            });
          }else {
            addContract(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.fileList = [];
              this.getList();
            })
          }
        }
      });
    },
    /** 作废按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认作废编号为"' + id + '"的合同？').then(function() {
        return delContract(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("作废成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
